# coding:utf-8

import os
import time
import set_env_path     # 请勿删除

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker


Base = declarative_base()
engine = create_engine(
    os.getenv('DATABASE_URL')
    or 'mysql+pymysql://root:@127.0.0.1/wph_www_prod?charset=utf8'
)
Session = sessionmaker(bind=engine)
session = Session()


def sync_user_tags():
    """
    create by ld_wu 2017-09-01
    原抢套餐表中的area_id只支持输入省份
    目前需要area_id的内容更新为省份所在城市
    :return:
    """
    select_engineer_sql = """
    select id from user where type=100
    """

    select_tags_sql = """
        select id, user_id, install, repair, rent from user_tags
    """

    create_tag_sql = """
    insert into user_tags (user_id, install, repair, rent, 
    created_at, updated_at, follow_state, aspiration, gold_aspiration, 
    supplier_aspiration, pay_aspiration, paid_feel, mastery, scale,
    contact_frequency, injured, few_order, small_order, fake_order,
    crowd_order, unfair_rule
    )
     values(
     :user_id, true, true, true, :created_at, :created_at,
     :default_int, :default_int, :default_int, :default_int,
     :default_int, :default_int, :default_int, :default_int,
     :default_int, :default_int, :default_bool, :default_bool,
     :default_bool, :default_bool, :default_bool
     )
    """

    update_tag_sql = """
        update user_tags set install=true, rent=true, repair=true where id=:id
    """

    engineers = session.execute(select_engineer_sql).fetchall()
    tags = session.execute(select_tags_sql).fetchall()

    tag_map = {each.user_id for each in tags}
    update_tag_map = {
        each.id: each
        for each in tags if not (each.install or each.rent or each.repair)
    }
    empty_tag_users = [each.id for each in engineers if each.id not in tag_map]

    # 标签记录为空的需要写入默认标签信息
    for each_id in empty_tag_users:
        print(each_id)
        time_stamp = int(time.time())
        session.execute(
            create_tag_sql,
            {
                'user_id': each_id,
                'created_at': time_stamp,
                'default_int': 0,
                'default_bool': False
            }
        )

        session.commit()

    # 业务范围未选的需要更新为全选
    for tag_id, tag in update_tag_map.items():
        print(tag.user_id)
        session.execute(
            update_tag_sql,
            {
                'id': tag_id
            }
        )

        session.commit()


if __name__ == '__main__':
    sync_user_tags()
